/* creates binary image libraries from apple rags */
/* revised July 1992 to also include chunks of binary data */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <dos.h>
#include <bios.h>
#include <io.h>
#include <malloc.h>
#include <conio.h>


unsigned char far *raw;  /* image */
int BIN =0;


int ribcook(char *name,char *name2)
{
    FILE *fp,*fp2;
    int fh;

    long counter=0,target,orgsize=0l;
    unsigned targetint;
    unsigned char c;

    char *wordptr;
    char buf0[66],buf1[66],buf2[66],buf3[66],buf4[66];
    char buffer[128];

    if((fp=fopen(name,"rb"))==NULL)return -1;
    target=filelength(fileno(fp));
    fclose(fp);

    targetint=(unsigned )target;
    raw= _fmalloc(targetint);

    fh = open(name,O_RDONLY|O_BINARY);
    read(fh,raw,targetint);
    close(fh);

    /* now open the library files */

    strcpy(buf1,name);
    strcpy(buf0,name2);

    wordptr=strtok(buf1,".");
    wordptr=strtok(buf0,".");

    sprintf(buf2,"%s.RAP",buf0); /* map  file   */
    sprintf(buf3,"%s.RIB",buf0); /* data file   */
    sprintf(buf4,"%s.BAK",buf0); /* update info */

    fp=fopen(buf2,"a");
    if((fp2=fopen(buf3,"rb"))!=NULL)
    {
        orgsize=filelength(fileno(fp2));
        fclose(fp2);
    }
    else
    {
        /* the first time we print a library filename */
     fprintf(fp,"/* graphics library map file for library %s */\n\n",buf3);
     fprintf(fp,"char *%s_LIB= \"%s\";\n\n",buf0,buf3);
     fprintf(fp,"\n\n");
     fprintf(fp,"\n\n\n\n\n",buf0);

    }

    /* finish writing the tracking data and close the map file */

    if(BIN==0)
    fprintf(fp,
     "/* lib info for character array created from fragment %s */\n",
    name);
    else
    fprintf(fp,
     "/* lib info for character array created from binary file %s */\n",
    name);

    if(BIN==0)target-=2;
    fprintf(fp,"#define %s_SIZE   %ld\n",buf1,target);
    if(BIN==0)fprintf(fp,"#define %s_WIDTH  %d\n",buf1,*raw++);
    if(BIN==0)fprintf(fp,"#define %s_HEIGHT %d\n",buf1,*raw++);
    fprintf(fp,"#define %s_OFFSET %ld\n\n",buf1,orgsize);
    fclose(fp);


    fp2=fopen(buf3,"ab");
    for(counter=0;counter<target;counter++)
        {
        orgsize++;
        fputc(raw[counter],fp2);
        }
        fclose(fp2) ;
    _ffree(raw);

    /* update the record file */
    remove(buf4);
    rename(buf2,buf4);

    fp= fopen(buf4,"r");
    fp2=fopen(buf2,"w");

    for(fh=0;fh<8;fh++)
    {
     fgets(buffer,128,fp);
     fputs(buffer,fp2);
     }

     fgets(buffer,128,fp);
     fgets(buffer,128,fp);
     fprintf(fp2,"#define %s_SIZE %ld /* library size in bytes */\n\n",
     buf0,orgsize);
     while(fgets(buffer,128,fp)!=NULL)fputs(buffer,fp2);
     fclose(fp);
     fclose(fp2);
    return 0;

}



main(int argc, char *argv[])
{
    switch(argc)
    {
        case 4: BIN=1;
        case 3: ribcook(argv[2],argv[1]);
    }
    exit(0);

}


